package com.huangmingfu;

import java.util.Random;
import java.util.Stack;

/**
 * @Author: 黄名富
 * @Description: 备忘录模式
 * @CreationDate: 2024/6/2
 */
public class MementoPattern {

    public static void main(String[] args) {
        String[] colors = {"red","blue","green","pink","black"};
        Button button = new Button();
        Random random = new Random();
        MementoCareTaker<ButtonMemento> careTaker = new MementoCareTaker<>();
        for (int i = 0; i < 10; i++) {
            button.setColor(colors[random.nextInt(colors.length)]);
            button.setPositionX(random.nextDouble());
            careTaker.pushMemento(button.createMemento());
        }
        button.restoreFromMemento(careTaker.getMemento(2));
        System.out.println(button);
        button.restoreFromMemento(careTaker.getMemento(3));
        System.out.println(button);
        button.restoreFromMemento(careTaker.getMemento(1));
        System.out.println(button);
    }

    private static class Button {
        private String color;
        private Double positionX;

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        public Double getPositionX() {
            return positionX;
        }

        public void setPositionX(Double positionX) {
            this.positionX = positionX;
        }

        public ButtonMemento createMemento() {
            return new ButtonMemento(color,positionX);
        }

        public void restoreFromMemento(ButtonMemento memento) {
            this.color = memento.getColor();
            this.positionX = memento.positionX;;
        }

        @Override
        public String toString() {
            return "Button{" +
                    "color='" + color + '\'' +
                    ", positionX=" + positionX +
                    '}';
        }
    }

    private static class ButtonMemento {
        private final String color;
        private final Double positionX;

        public ButtonMemento(String color, Double positionX) {
            this.color = color;
            this.positionX = positionX;
        }

        public String getColor() {
            return color;
        }

        public Double getPositionX() {
            return positionX;
        }

    }

    private static class MementoCareTaker<T> {

        private final Stack<T> stack = new Stack<>();

        public void pushMemento(T t) {
            stack.push(t);
        }

        public T getMemento(int num) {
            T t = null;
            while (num-- > 0 && !stack.isEmpty()) {
                t = stack.pop();
            }
            return t;
        }

    }

}
